
using Newtonsoft.Json.Linq;
using UnityEngine.SceneManagement;
using UnityEngine;
using System;
using System.IO;

public class ParseScene : ParseObjectHandle<Scene>
{
    public override void Prase(ExportSetting ExportSetting, Scene obj, JArray jArray)
    {
        JToken cocosObjectConfig = ExportSetting.CocosObjectConfig;
        JToken cocosMetaConfig = ExportSetting.CocosMetaConfig;
        JToken sceneAssetToken = cocosObjectConfig["cc.SceneAsset"].DeepClone();
        JToken sceneToken = cocosObjectConfig["cc.Scene"].DeepClone();
        JToken sceneGlobal = cocosObjectConfig["cc.SceneGlobals"].DeepClone();
        JToken ambientInfoToken = cocosObjectConfig["cc.AmbientInfo"].DeepClone();
        JToken shadowInfoToken = cocosObjectConfig["cc.ShadowsInfo"].DeepClone();
        JToken skyinfoToken = cocosObjectConfig["cc.SkyboxInfo"].DeepClone();
        JToken fogInfoToken = cocosObjectConfig["cc.FogInfo"].DeepClone();
        jArray.Add(sceneAssetToken);
        jArray.Add(sceneToken);
        jArray.Add(sceneGlobal);
        jArray.Add(ambientInfoToken);
        jArray.Add(shadowInfoToken);
        jArray.Add(skyinfoToken);
        jArray.Add(fogInfoToken);

        sceneAssetToken["scene"] = AssetHelper.CreateIdJObject(1);
        sceneToken["_id"] = AssetHelper.GetObjectUUID(obj);
        sceneToken["_globals"] = AssetHelper.CreateIdJObject(2);
        sceneGlobal["ambient"] = AssetHelper.CreateIdJObject(3);
        sceneGlobal["shadows"] = AssetHelper.CreateIdJObject(4);
        sceneGlobal["_skybox"] = AssetHelper.CreateIdJObject(5);
        sceneGlobal["fog"] = AssetHelper.CreateIdJObject(6);

        JArray sceneChildren = sceneToken["_children"] as JArray;
        sceneChildren.Clear();

        var gameObjects = obj.GetRootGameObjects();
        foreach (var gameObject in gameObjects)
        {
            if (ExportSetting.IgnoreNoActive && !gameObject.activeSelf)
            {
                continue;
            }
            int nodeTokenIndex = jArray.Count;
            ExportToDispatcher.Instance.ParseObjectToCocos(gameObject, ExportSetting, jArray);
            sceneChildren.Add(AssetHelper.CreateIdJObject(nodeTokenIndex));
            jArray[nodeTokenIndex]["_parent"] = AssetHelper.CreateIdJObject(1);
        }
        var exportPath = $"{ExportSetting.ExportPath}/{obj.name}.scene";
        if (!AssetHelper.IsCanOverride(ExportSetting, exportPath))
        {
            return;
        }
        File.WriteAllText(exportPath, jArray.ToString());
        Debug.Log($"导出场景{obj.name}.scene成功！");
    }
}